package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.jaxb.SpringDataJaxb;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //封装属性
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        //判断购物车和地址是否为空
        // 如果为空，则抛出异常
        ShoppingCart cart = new ShoppingCart();
        cart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> list = shoppingCartMapper.list(cart);
        if (list == null || list.isEmpty()){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        if (ordersSubmitDTO.getAddressBookId() == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //设置订单数据并插入数据库
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        //生成10位随机数字串作为订单号
        orders.setNumber(generate10DigitNumber());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        String address = addressBook.getProvinceName() + addressBook.getCityName()
                + addressBook.getDistrictName() + addressBook.getDetail();
        orders.setAddress(address);
        //TODO 用户名未创建此处无法进行封装
        orderMapper.insert(orders);
        //封装菜品订单数据
        Long OrderId = orders.getId();
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart c : list) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(OrderId);
            orderDetail.setName(c.getName());
            orderDetail.setImage(c.getImage());
            orderDetail.setDishId(c.getDishId());
            orderDetail.setSetmealId(c.getSetmealId());
            orderDetail.setDishFlavor(c.getDishFlavor());
            orderDetail.setNumber(c.getNumber());
            orderDetail.setAmount(c.getAmount());
            orderDetails.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetails);
        //封装结果并返回
        return OrderSubmitVO.builder()
                .id(OrderId)
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
    }

    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
         PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
         Page<Orders> page = orderMapper.conditionSearch(ordersPageQueryDTO);
         return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public OrderSearchVO getById(Long id) {
        OrderSearchVO orderSearchVO = new OrderSearchVO();
        List<Orders> list = orderMapper.getById(id);
        BeanUtils.copyProperties(list.get(0), orderSearchVO);
        List<OrderDetail> orderDetails = orderDetailMapper.listByOderId(id);
        orderSearchVO.setOrderDetailList(orderDetails);
        return orderSearchVO;

    }

    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(orderMapper.countByStatus(Orders.TO_BE_CONFIRMED));
        orderStatisticsVO.setConfirmed(orderMapper.countByStatus(Orders.CONFIRMED));
        orderStatisticsVO.setDeliveryInProgress(orderMapper.countByStatus(Orders.DELIVERY_IN_PROGRESS));
        return orderStatisticsVO;
    }

    @Override
    public void complete(Long id) {
        orderMapper.updateStatus(id, Orders.COMPLETED);
    }

    @Override
    public void delivery(Long id) {
        orderMapper.updateStatus(id, Orders.DELIVERY_IN_PROGRESS);
    }

    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        orderMapper.updateStatus(ordersConfirmDTO.getId(), Orders.CONFIRMED);
    }

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        orderMapper.updateStatus(ordersCancelDTO.getId(), Orders.CANCELLED);
        orderMapper.updatecancelReason(ordersCancelDTO.getId(), ordersCancelDTO.getCancelReason());
    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        orderMapper.updateStatus(ordersRejectionDTO.getId(), Orders.CANCELLED);
        orderMapper.updateRejectionReason(ordersRejectionDTO.getId(), ordersRejectionDTO.getRejectionReason());
    }

    @Override
    public PageResult conditionSearchWithUserId(OrdersPageQueryDTO ordersPageQueryDTO) {
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<OrderSearchVO> page = orderMapper.conditionSearchWithUserId(ordersPageQueryDTO);
        page.getResult().forEach(orderSearchVO -> {
            List<OrderDetail> orderDetails = orderDetailMapper.listByOderId(orderSearchVO.getId());
            orderSearchVO.setOrderDetailList(orderDetails);
        });
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    @Transactional
    public void repetion(Long id) {
        OrderSearchVO orderSearchVO = getById(id);
        Orders orders = new Orders();
        //设置部分有效的订单数据
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setOrderTime(LocalDateTime.now());
        orders.setNumber(generate10DigitNumber());
        orders.setAddress(orderSearchVO.getAddress());
        orders.setAddressBookId(orderSearchVO.getAddressBookId());
        orders.setAmount(orderSearchVO.getAmount());
        orders.setConsignee(orderSearchVO.getConsignee());
        orders.setPhone(orderSearchVO.getPhone());
        orders.setUserId(orderSearchVO.getUserId());
        orders.setUserName(orderSearchVO.getUserName());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setPayMethod(1);
        orders.setRemark(orderSearchVO.getRemark());
        orders.setUserName(orderSearchVO.getUserName());
        orders.setDeliveryStatus(1);
        orders.setPackAmount(orderSearchVO.getPackAmount());
        orders.setTablewareNumber(orderSearchVO.getTablewareNumber());
        orders.setTablewareStatus(orderSearchVO.getTablewareStatus());
        orderMapper.insert(orders);
        orderSearchVO.getOrderDetailList().forEach(orderDetail -> {
            orderDetail.setOrderId(orders.getId());
        });
        orderDetailMapper.insertBatch(orderSearchVO.getOrderDetailList());

    }

    public String generate10DigitNumber() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        // 第一位确保不为 0
        sb.append(random.nextInt(9) + 1);
        // 剩余 9 位
        for (int i = 0; i < 9; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );
        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }
}
